package com.mikepenz.app.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.android.volley.VolleyError;
import com.mikepenz.app.R;
import com.mikepenz.app.activity.MainActivity;
import com.mikepenz.app.activity.ParkListActivity;
import com.mikepenz.bean.ParkBean;
import com.mikepenz.interactor.MainFragInteractor;
import com.mikepenz.interactor.imp.MainFragInteractorImp;
import com.mikepenz.presenter.listener.RequestListener;
import com.mikepenz.presenter.MainFragPresenter;
import com.mikepenz.presenter.imp.MainFragPresenterImp;
import com.mikepenz.utils.CookicUntil;
import com.mikepenz.view.MainFragView;
import com.quickdv.activity.fragment.MapFragment;
import com.quickdv.until.AlertHelper;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MainFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends MapFragment implements LocationSource, AMapLocationListener ,MainFragView{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private LocationManagerProxy mLocationManagerProxy;
    private OnLocationChangedListener mListener;
    private ProgressDialog load;
    MainFragPresenter presenter;
    MainFragInteractor interactor;
    LatLng latlng;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        presenter =new MainFragPresenterImp(activity.getApplication(),this);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        super.onCreate(savedInstanceState);

    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    protected void initView() {
        mapView = findView(R.id.map);
        Button button = findView(R.id.want_tenancy);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(activity, ParkListActivity.class);
                Bundle bundle = new Bundle();
                if(latlng!=null) {
                    bundle.putDouble("lat", latlng.latitude);
                    bundle.putDouble("lng", latlng.longitude);
                }
                else {
                    bundle.putDouble("lat", 34.8227600000);
                    bundle.putDouble("lng", 113.6424760000);
                }
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
//        presenter.getParking(new LatLng(0, 0));
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        interactor = new MainFragInteractorImp(activity, new RequestListener<List<ParkBean>>() {
            @Override
            public void Success(String tag, List<ParkBean> result) {
                dismissLoad();
                drawPostions(result);
            }

            @Override
            public void Error(String tag, String error) {

            }

            @Override
            public void Exception(String tag, VolleyError error) {

            }
        });
    }

    protected void init() {
        super.init();
        setUpMap();
        load = new AlertHelper(activity).LoadingAlert();

    }

    @Override
    protected int getLayoutViewID() {
        return R.layout.fragment_main;
    }

    /**
     * 绘制系统默认的1种marker背景图片
     */
    @Override
    public void drawPostions(List<ParkBean> parks) {
        ((MainActivity) activity).setTitle("附近停车场（"+parks.size()+"）");

        for (ParkBean p :parks) {
            MarkerOptions options = new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
                    .position(new LatLng(p.getLat(), p.getLng())).title(p.getParkName())
                    .draggable(true).period(10);
            aMap.addMarker(options);
        }
    }

    @Override
    public void clearPostions() {
        aMap.clear();
    }

    @Override
    public void dismissLoad() {
        if (load == null || !load.isShowing()) return;
        load.dismiss();
    }

    @Override
    public void showLoad() {
        if (load == null || load.isShowing()) return;
        load.show();
    }

    @Override
    public void showError(String error) {
        Toast.makeText(activity, error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void setCLickListener() {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
        // 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        log.v("MainFragment","this is loactionChagaed");
            if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
                //获取位置信息
                Double geoLat = amapLocation.getLatitude();
                Double geoLng = amapLocation.getLongitude();
                latlng =new LatLng(geoLat, geoLng);
                        changeCamera(
                        CameraUpdateFactory.newCameraPosition(new CameraPosition(
                                latlng , 18, 0, 30)), null);
                mListener.onLocationChanged(amapLocation);
                interactor.getParking(latlng, null, 1);
                CookicUntil.setLatLng(latlng);
                deactivate();
            }

    }

    private void changeCamera(CameraUpdate update, AMap.CancelableCallback callback) {
        //初始化地图中心位置
        aMap.animateCamera(update, 1000, callback);
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mLocationManagerProxy == null) {
            mLocationManagerProxy = LocationManagerProxy.getInstance(activity);
            //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
            //在定位结束后，在合适的生命周期调用destroy()方法
            //其中如果间隔时间为-1，则定位只定一次
            mLocationManagerProxy.requestLocationData(
                    LocationProviderProxy.AMapNetwork, -1, 500, this);
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destroy();
        }
        mLocationManagerProxy = null;
    }


}
